package com.tf_cut.admin.util;

import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5 工具类
 */
@Slf4j
public class MD5Util {

    /**
     * 生成MD5加密串
     */
    public static String getMD5(String message) {
        String md5 = "";
        try {
            //创建一个md5算法对象
            log.info("md5原串："+message);
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageByte = message.getBytes(StandardCharsets.UTF_8);
            //获得MD5字节数组,16*8=128位
            byte[] md5Byte = md.digest(messageByte);
            //转换为16进制字符串
            md5 = ByteUtil.bytesToHex(md5Byte);
            log.info("md5加密串："+md5);
        } catch (Exception e) {
            log.error("getMD5报错了！", e);
        }
        return md5;
    }
    
    
	/**
	 * JDK Md5加密
	 */
	public static String md5(String target){
		StringBuilder stringBuilder = new  StringBuilder();
		MessageDigest digest = null;
		try {
			digest = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		byte[] digest2 = digest.digest(target.getBytes());
		for (byte b : digest2) {
			int l = b & 0xff;
			if(l<16){
				stringBuilder.append("0");
			}
			stringBuilder.append(Integer.toHexString(l));
		}
		return stringBuilder.toString();
	}
    

    /**
     * 验证方法
     * @param text 明文
     * @param md5 密文
     * @return 对比结果
     */
    public static boolean verify(String text,String md5){
        log.info("参数加密串："+md5);
        return md5.equals(getMD5(text));
    }

    public static String getMD5Lower(String message) {
        String md5 = "";
        try {
            //创建一个md5算法对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageByte = message.getBytes(StandardCharsets.UTF_8);
            //获得MD5字节数组,16*8=128位
            byte[] md5Byte = md.digest(messageByte);
            //转换为16进制字符串
            md5 = ByteUtil.bytesToHexLower(md5Byte);
        } catch (Exception e) {
            log.error("getMD5报错了！", e);
        }
        return md5;
    }

}
